package com.hyj.springcloud.controller;

import com.hyj.springcloud.entities.CommonResult;
import com.hyj.springcloud.entities.Payment;
import com.hyj.springcloud.lb.LoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@Slf4j
public class OrderController {
    //    单机,通过ip+port访问
//    private static final String PAYMENT_URL = "http://localhost:8001";
    //    集群,同名微服,有两个端口.8001,8002,通过微服名字访问,2.restTemplate要加上loadBalance功能.
    private static final String PAYMENT_URL = "http://cloud-provider-service";

    //    @Autowired
//    OrderService orderService;
    /**
     * 1.不再是mvc,而是不同模块间调用,用restTemplate,2.要restT,可以@Bean注入(偷懒直接写在这,不推荐),也可以配置类中配置好.
     */
    @Autowired
    RestTemplate restTemplate;
    //my
    @Autowired
    LoadBalance loadBalance;
    @Autowired
    DiscoveryClient discoveryClient;

    //http://localhost/consumer/payment/create?serial=consTest4 这么写浏览器默认用get,@PostMapping不行.provider接收到的payment对象null,db插入为null
    //弹幕:provider加@RequestBody,数据库插入数据成功.不再是null了
    //???   localhost:8001/payment/create?serial=firstTest 这么写provider那边却可以,???
    @GetMapping("/consumer/payment/create")
    public CommonResult create(Payment payment) {
//        responseEntity学习。
//        ResponseEntity<CommonResult> commonResultResponseEntity = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
//        if (commonResultResponseEntity.getStatusCode().is2xxSuccessful()) {
//            System.out.println("commonResultResponseEntity.getBody() = " + commonResultResponseEntity.getBody());
//        }
        //url,参数,返回结果class
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    /**
     * test LoadBalance
     */
    @GetMapping("/consumer/payment/lb")
    public String getLoadBalance() {
        //通过微服名字获取其下所有实例.
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("cloud-provider-service");
        return null;
    }

}
